<template>
  <div class="app-main-container">
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getList(1)" @clear="clearList">
      <template v-if="meta.indexOf('CourseOrderExp') > -1" #btns>
        <el-button :loading="subLoading" type="primary" @click="handleExport">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table ref="table" v-loading="listLoading" :data="list" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-tableb">
      <el-table-column align="center" :label="$t('message.ddbh')" min-width="220" show-overflow-tooltip prop="orderId">
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.memberInfo')" min-width="250" prop="memberInfo" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.kcmc')" min-width="140" prop="courseName" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.kclx')" prop="payMethod" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.flag == '1'">{{ $t('message.spk') }}</span>
          <template v-if="scope.row.flag == '2'">
            <span v-if="scope.row.courseType == '1'">{{ $t('message.cgk') }}</span>
            <span v-if="scope.row.courseType == '3'">{{ $t('message.cgk') }}</span>
            <span v-if="scope.row.courseType == '4'">{{ $t('message.sjk') }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.kcjgy')" prop="price" min-width="120" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.zffs')" prop="payMethod" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.payMethodName }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.sfje')" prop="allPrice" min-width="100" />
      <el-table-column align="center" :label="$t('message.ytkje')" prop="refundPrice" min-width="100" />
      <el-table-column align="center" :label="$t('message.createTime')" prop="createTime" min-width="160" />
      <el-table-column align="center" :label="$t('message.paytime')" prop="payTime" min-width="160" />
      <el-table-column align="center" :label="$t('message.ddly')" prop="channelTypeName" min-width="100" />
      <el-table-column align="center" :label="$t('message.bz')" prop="note" min-width="120" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.czr')" prop="orderOperator" min-width="120" />
      <el-table-column align="center" :label="$t('message.ddzt')" prop="orderStatus" min-width="100" fixed="right">
        <template slot-scope="scope">
          {{
            scope.row.statusName
          }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.caozuo')" :width="$i18n.locale === 'ZH'? 180 : 260" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="scope.row.orderStatus == 3 && meta.indexOf('OfflinecoursesOrderRefund') > -1" v-preventReClick type="text" @click="rowClickRefound(scope.row)">{{ $t('message.qxdd') }} </el-button>
            <el-button v-if="
                scope.row.orderStatus == 3 &&
                  meta.indexOf('CoursePrinterOrder') > -1
              " v-preventReClick type="text" @click="rowPrint(scope.row.orderId)">{{ $t('message.dyxp') }}</el-button>
            <el-button v-if="scope.row.orderStatus == 0 && meta.indexOf('CourseContinuePay') > -1" v-preventReClick type="text" @click="rowClickGoOn(scope.row)">{{ $t('message.jxzf') }}</el-button>
            <el-button v-if="
                scope.row.orderStatus == 0 &&
                  meta.indexOf('CourseCancelPay') > -1
              " v-preventReClick type="text" @click="rowCancel(scope.row)">{{ $t('message.qxzf') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations :total="total" :page="pagination.page" @current-change="getList" @SizeChange="handleSizeChange" />

    <el-dialog :title="$t('message.tk')" :visible.sync="RefoundModal" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog" width="800px">
      <div>
        <div class="mb20">
          <span>{{ $t('message.tklx') }}：</span>
          <el-radio v-model="refundType" label="0">{{ $t('message.jtk') }}</el-radio>
          <el-radio v-model="refundType" label="1">{{ $t('message.tktk') }}</el-radio>
        </div>
        <el-table ref="RefoundTableRef" :data="RefoundInfo" border fit :header-row-class-name="'table-header'" class="doumee-element-table mb30" @selection-change="RefoundSelectionChange">
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column align="center" :label="$t('message.xyxm')" prop="studentName" min-width="120" show-overflow-tooltip />
          <el-table-column v-if="activeCourseType == '4'" align="center" :label="$t('message.keshi')" prop="timeQuantum" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.kcjg')" prop="coursePrice" min-width="80" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.num')" prop="num" min-width="60" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.sfk')" prop="price" min-width="80" show-overflow-tooltip />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RefoundModal = false">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick :loading="RefoundLoading" type="primary" @click="handleRefound">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t('message.tkxq')" :visible.sync="RefoundDetailModal" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog" width="800px">
      <div>
        <div class="mb20">
          <span>{{ $t('message.tklx') }}：</span>
          <span> {{ refundType === "0" ? $t('message.jtk') : $t('message.tktk') }} </span>
        </div>
        <el-table ref="RefoundTableRef" :data="selectedCourseList" border fit :header-row-class-name="'table-header'" class="doumee-element-table mb30">
          <el-table-column align="center" :label="$t('message.xyxm')" prop="studentName" min-width="120" show-overflow-tooltip />
          <el-table-column v-if="activeCourseType == '4'" align="center" :label="$t('message.keshi')" prop="timeQuantum" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.kcjg')" prop="coursePrice" min-width="80" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.num')" prop="num" min-width="60" show-overflow-tooltip />
          <el-table-column align="center" :label="$t('message.sfk')" prop="price" min-width="80" show-overflow-tooltip />
        </el-table>
        <div class="df_ac">
          <span>{{ $t('message.tkje') }}：</span>
          <el-input v-model="changePrice" :disabled="!isChangePrice" oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1');" type="text" class="w200 mr20" />
          <el-checkbox v-model="isChangePrice" class="mr20">{{ $t('message.gaijia') }}</el-checkbox>
          <!-- <span class="ml20 placeholder9">{{ $t('message.bzxszfjeylfh') }}</span> -->
        </div>
        <div class="df_ac mt20">
          <span>{{ $t('message.tkyy') }}：</span>
          <el-input v-model="remarkRefound" class="w400" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RefoundDetailModal = false">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick :loading="RefoundLoading" type="primary" @click="confirmRefound">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <Detail ref="DetailRef" />
    <CourseTem v-if="isPrint" ref="CourseTemRef" />
    <orderDialog ref="orderRef" @orderSuccess="getList()" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import store from '@/store'
import { courseOrderEx, courseOrderVenueList, getOrderTypeQuery, courseOrderCancel, courseRefund, refundCourse, allConfigList, courseOrderRefund, courseOrderRefundAc, printOrder } from '@/api'
import { queryFormConfig } from './config'
import QueryForm from '@/components/QueryForm'
import dayjs from 'dayjs'
import Detail from './detail.vue'
import orderDialog from '@/components/order'
import CourseTem from '@/components/printTem/course.vue'
export default {
  name: 'OfflinecoursesOrder',
  components: {
    QueryForm,
    Detail,
    orderDialog,
    CourseTem
  },
  data () {
    return {
      RefoundModal: false,
      RefoundLoading: false,
      RefoundDetailModal: false,
      isPrint: false,
      isChangePrice: false,
      changePrice: 0,
      refundType: '1',
      activeOrderId: '',
      activeCourseType: '',
      remarkRefound: '',
      RefoundInfo: [],
      selectedCourseList: [],

      modalDialog: store.getters.dialog,
      subLoading: false,
      queryFormConfig,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      filters: {},
      listLoading: true,
      show: false,
      orderId: '',
      allPayMethedList: [],
      form: {},
      rules: {
        price: [
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            required: true,
            message: this.$t('message.qsrzrksdj'),
            trigger: 'blur'
          }
        ],
        info: [
          { required: true, message: this.$t('message.fyyxxtk'), trigger: 'blue' }
        ],
        isAgree: [
          { required: true, message: this.$t('message.qxzcwsfty'), trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.pdgj()
    let time = []
    const start = new Date()
    const end = new Date()
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
    time = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
    this.$set(this.filters, 'Times', time)
    this.getList(1)
    this.getOrderStatusList()
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    getOrderStatusList () {
      getOrderTypeQuery({ param: {} }).then(res => {
        this.queryFormConfig.formItems[6].options = res.recordList || []
      })
    },
    rowClickGoOn (row) {
      this.$refs.orderRef.continuePay(row, 'studentPay')
    },
    handleExport () {
      this.subLoading = true
      const { filters } = this
      const venueId = sessionStorage.getItem('venueId')
      filters.flag = '2'
      if (filters.Times && filters.Times.length > 0) {
        filters.startTime = filters.Times[0]
        filters.endTime = filters.Times[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      courseOrderEx({ param: { venueId, ...filters } })
        .then((res) => {
          this.subLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => {
          this.subLoading = false
        })
    },
    getList (page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      filters.flag = '2'
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.Times && filters.Times.length > 0) {
        filters.startTime = filters.Times[0]
        filters.endTime = filters.Times[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      courseOrderVenueList({ pagination, param: { venueId, ...filters } })
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    rowCancel (row) {
      this.$confirm(this.$t('message.qxzftc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      }).then(() => {
        courseOrderCancel({
          param: { orderId: row.orderId }
        }).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.qxddcg'))
          this.getList()
        })
      })
    },
    handleDetail (row) {
      this.$refs.DetailRef.getOrderDetail(row)
      this.$refs.DetailRef.isShow = true
    },
    rowPrint (id) {
      this.$confirm(this.$t('message.dyxptc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          this.isPrint = true
          if (window.Android) {
            Android.print('COURSETPML', id, '');
            return
          }
          printOrder({
            param: {
              contentMap: {},
              venueId: sessionStorage.getItem('venueId'),
              workId: id,
              templateCode: 'COURSETPML'
            }
          })
            .then((res) => {
              if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
                res.record.dataList.forEach(item => {
                  this.$refs.CourseTemRef.obj = { ...item }
                  setTimeout(() => {
                    this.$refs.CourseTemRef.print()
                  }, 300)
                  setTimeout(() => {
                    this.isPrint = false
                  }, 500)
                })
              } else {
                this.isPrint = false
              }
            })
            .catch(() => {
              this.isPrint = false
            })
        })
        .catch(() => {
          // this.$message.info('操作已取消')
        })
    },
    handleRefound () {
      const { refundType, selectedCourseList } = this
      if (selectedCourseList.length === 0) return this.$message.warning(this.$t('message.qxxzxtkkc'))
      const orderId = this.activeOrderId
      const detailIds = selectedCourseList.map(i => i.studentId)
      const timeStudentIds = selectedCourseList.map(i => i.timeStudentId)

      const param = {
        orderId,
        refundType,
        detailIds,
        type: '0',
        timeStudentIds
      }
      this.RefoundLoading = true
      courseOrderRefundAc({ param }).then(res => {
        this.RefoundLoading = false
        if (res.errorCode !== '000000') return
        this.changePrice = res.record
        this.RefoundModal = false
        this.RefoundDetailModal = true
        this.remarkRefound = ''
      }, () => {
        this.RefoundLoading = false
      })
    },
    confirmRefound () {
      const { refundType, selectedCourseList, changePrice, remarkRefound, isChangePrice } = this
      const orderId = this.activeOrderId
      const detailIds = selectedCourseList.map(i => i.studentId)
      const timeStudentIds = selectedCourseList.map(i => i.timeStudentId)
      if (changePrice === '' || changePrice === null || changePrice === undefined) {
        return this.$message.warning(this.$t('message.qsr') + this.$t('message.tkje'))
      }
      const param = {
        orderId,
        refundType,
        detailIds,
        timeStudentIds,
        type: '1',
        refundPrice: changePrice,
        remark: remarkRefound,
        isChange: isChangePrice ? '1' : '0'
      }
      this.RefoundLoading = true
      courseOrderRefundAc({ param }).then(res => {
        this.RefoundLoading = false
        if (res.errorCode !== '000000') return
        this.RefoundDetailModal = false
        this.$message.success(this.$t('message.tkcg'))
        this.getList()
      }, () => {
        this.RefoundLoading = false
      })
    },
    rowClickRefound (row) {
      courseOrderRefund({ param: { orderId: row.orderId } }).then((res) => {
        this.RefoundInfo = res.recordList || []
      })
      this.activeOrderId = row.orderId
      this.activeCourseType = row.courseType
      this.RefoundModal = true
    },
    RefoundSelectionChange (val) {
      this.selectedCourseList = val
    },
    handleSizeChange (value) {
      this.pagination.rows = value
      this.getList(1)
    },
    tke (e) {
      this.orderId = e.orderId
      this.show = true
    },
    tk (e) {
      const that = this
      this.$confirm(this.$t('message.tktc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      }).then(() => {
        courseRefund({ param: { orderId: e.orderId } })
          .then(res => {
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.tktcqr'))
              that.getList(1)
            }
          })
          .catch(() => { })
      })
    },
    pdgj () {
      allConfigList({ param: { type: '2', code: '1' } }).then(res => {
        if (res.errorCode === '000000') {
          this.allPayMethedList = res.recordList
          const arrb = res.recordList
          arrb.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[4].options = arrb
        }
      }).catch(err => {
        console.log(err)
      })
    },
    nameWithPayMethod (payM) {
      const obj = this.allPayMethedList.find(item => item.value === payM)
      if (obj) {
        return obj.name
      } else {
        return '-'
      }
    },
    onSubmit () {
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = {}
          param.orderId = that.orderId
          param.money = Number(that.form.price)
          param.note = that.form.info
          param.isAgree = that.form.isAgree
          that.$confirm(this.$t('message.tktc2'), this.$t('message.ts'), {
            confirmButtonText: this.$t('message.qd'),
            cancelButtonText: this.$t('message.qx'),
            type: 'warning'
          }).then(() => {
            refundCourse({ param })
              .then((res) => {
                if (res.errorCode === '000000') {
                  that.show = false
                  that.$message.success(this.$t('message.tkcg2'))
                  that.getList(1)
                }
              })
          })
            .catch(() => {
              // this.$message.info('已取消操作')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearList () {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>
